<template>
  <div class="ele-body">
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="日期:">
              <a-date-picker v-model:value="where.usageDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>
            </a-form-item>
            <a-form-item label="时间点:">
              <a-input v-model:value.trim="where.timePoint" placeholder="请输入时间点" allow-clear />
            </a-form-item>
            <a-form-item label="时间段:">
              <a-input v-model:value.trim="where.timeSlot" placeholder="请输入时间段" allow-clear />
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false" class="table-height">
        <ele-pro-table
          ref="table"
          row-key="id"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          v-model:selection="selection"
          :scroll="{ x: 'max-content' }"
          :pagination="{
            pageSize: 96,
            showSizeChanger: true,
            pageSizeOptions: ['96','195','288','384'],
            showTotal: total => `共 ${total} 条`
          }"
          :pageSize="96"
        >
          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space>
              <a-button type="primary" @click="openEdit()">
                <template #icon>
                  <plus-outlined />
                </template>
                <span>新建</span>
              </a-button>
              <a-button type="primary" @click="exportToExcel">
                <template #icon>
                  <export-outlined/>
                </template>
                <span>导出Excel</span>
              </a-button>
            </a-space>
          </template>

          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">修改</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

    <!-- 编辑弹窗 -->
    <qyuanPowerSdDayAheadClearedTotalEnergy-edit v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

<script>
import { message } from 'ant-design-vue';
import {ExportOutlined, PlusOutlined} from '@ant-design/icons-vue';
import { QyuanPowerSdDayAheadClearedTotalEnergyApi } from '@/api/qyuanPowerSdDayAheadClearedTotalEnergy/QyuanPowerSdDayAheadClearedTotalEnergyApi';
import QyuanPowerSdDayAheadClearedTotalEnergyEdit from './qyuan_power_sd_day_ahead_cleared_total_energy_edit.vue';
import {saveAs} from 'file-saver'; // 注意大小写
import * as XLSX from 'xlsx';
import dayjs from 'dayjs'

export default {
  name: 'QyuanPowerSdDayAheadClearedTotalEnergy',
  components: {
    ExportOutlined,
    PlusOutlined,
    QyuanPowerSdDayAheadClearedTotalEnergyEdit
  },
  async mounted() {
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          key: 'index',
          width: 48,
          hideInSetting: true,
          customRender: ({ index }) => this.$refs.table.tableIndex + index
        },
        {
          title: '日期',
          dataIndex: 'usageDate',
          customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD') // 直接调用[9](@ref)
        },
        {
          title: '时间点',
          dataIndex: 'timePoint'
        },
        {
          title: '时间段',
          dataIndex: 'timeSlot'
        },
        {
          title: '交易节点电量',
          dataIndex: 'tradingNodeEnergy'
        },
        {
          title: '交易总电量',
          dataIndex: 'tradingEnergy'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD') // 直接调用[9](@ref)
        },
        {
          title: '操作',
          key: 'action',
          width: 120,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author 我是谭先生🐻
     * @date 2025/03/14 16:23
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author 我是谭先生🐻
     * @date 2025/03/14 16:23
     */
    reset() {
      this.where.usageDate = {};
      this.where.timePoint = {};
      this.where.timeSlot = {};
      this.reload();
    },

    /**
     * 删除
     *
     * @author 我是谭先生🐻
     * @date 2025/03/14 16:23
     */
    async remove(row) {
      const result = await QyuanPowerSdDayAheadClearedTotalEnergyApi.delete({ id: row.id });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author 我是谭先生🐻
     * @date 2025/03/14 16:23
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },/**
     * 导出表格数据到Excel
     */
    exportToExcel() {
      // 获取表格DOM元素（处理Ant Design固定列问题）
      const table = this.$refs.table.$el.cloneNode(true);
      table.querySelectorAll('.ant-table-fixed').forEach(el => el.remove());

      // 获取数据行
      const rows = table.querySelectorAll('.ant-table-row');
      if (rows.length === 0) {
        message.warning('当前表格无数据可导出');
        return;
      }

      // 解析数据（带格式处理）
      const data = Array.from(rows).map(row => {
        const cells = row.querySelectorAll('td');
        return {
          // 添加\t前缀强制文本格式（解决科学计数法问题）
          日期: `\t${cells[2].innerText}`,       // 第2列
          时间点: `\t${cells[3].innerText}`, // 第3列
          时间段: `\t${cells[4].innerText}`,     // 第4列
          交易节点电量: `\t${cells[5].innerText}`,     // 第4列
          交易总电量: `\t${cells[6].innerText}`,     // 第4列
          创建时间: `\t${cells[7].innerText}`
        };
      });

      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(data, {
        header: ["日期", "时间点", "时间段", "交易节点电量", "交易总电量", "创建时间"]  // 与columns顺序保持一致
      });
      // 生成文件
      XLSX.utils.book_append_sheet(workbook, worksheet, "Electricity Forecast Data");
      const excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array'
      });

      try {
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
        saveAs(blob, `Electricity_Forecast_Data_${new Date().toISOString().slice(0,10)}.xlsx`);
      } catch (e) {
        console.error('导出失败:', e);
        message.error('导出失败，请检查控制台');
      }
    },

    /**
     * 获取表格数据
     *
     * @author 我是谭先生🐻
     * @date 2025/03/14 16:23
     */
    datasource({ page, limit, where, orders }) {
      return QyuanPowerSdDayAheadClearedTotalEnergyApi.findPage({ ...where, ...orders, pageNo: page, pageSize: 96 });
    }
  }
};
</script>
